<?php
require_once('wpts_functions.php');

if (current_user_can('manage_categories') ){

	function wpts_record_shoot(){
		$action = is_request('action');

		switch (strtolower($action)){
			case 'add shoot':
				if (! wp_verify_nonce(is_request('_wpts_noonce'), 'wpts_record_shoot') ) die('Security check');
				if (! is_request('shoot') ){
					echo '<div class="error">You must specify a Shoot</div>';
					$shoot = wpts_process_score( is_request('wpts_score') );
					wpts_record_shoot_form(is_request('user'), is_request('shoot'), $shoot['result'] );


					break;
				}

				$result = wpts_record_shoot_form_process(is_request('user'), is_request('shoot'), is_request('wpts_score') );
				if( ! $result[0] )
					var_dump($result);
				else{
					echo "Succesfully added a score of ".$result['post_title'].".  Add another below";
					wpts_record_shoot_form('', is_request('shoot') );
					$parent_id = get_term_by('id', is_request('shoot'), 'wpts_shoots', $output = ARRAY_A);
					echo wpts_empty_table_cache($parent_id['parent']);
				}
				break;

			case 'edit shoot':
				if (! wp_verify_nonce(is_request('_wpts_noonce'), 'wpts_record_shoot') ) die('Security check');
					if (! is_request('shoot') ){
					echo '<div class="error">You must specify a Shoot</div>';
					$shoot = wpts_process_score( is_request('wpts_score') );
					wpts_record_shoot_form(is_request('user'), is_request('shoot'), $shoot['result'] );
					break;
				}
				$result = wpts_record_shoot_form_process(is_request('user'), is_request('shoot'), is_request('wpts_score'), is_request('individual_shoot_id') );
				if( ! $result[0] )
					var_dump($result);
				else{
					echo "Succesfully Edited a score of ".$result['post_title']." to shoot.  Add another Below";
					wpts_record_shoot_form('', is_request('shoot') );
					$parent_id = get_term_by('id', is_request('shoot'), 'wpts_shoots', $output = ARRAY_A);
					wpts_empty_table_cache($parent_id['parent']);
				}
				break;

			default:
				wpts_record_shoot_form();
				break;

		}

	}

	function wpts_shoot_select_lists($shoot = false){
		$args= array('orderby' => 'name', 'order' => 'ASC',
        'hide_empty' => false, 'exclude' => '', 'exclude_tree' => '', 'include' => '',
        'number' => '', 'fields' => 'all', 'slug' => '', 'parent' => '',
        'hierarchical' => true, 'child_of' => 0, 'get' => '', 'name__like' => '',
        'pad_counts' => false, 'offset' => '', 'search' => '');
		$taxonomies = get_terms('wpts_shoots', $args);
		echo "<ul id='wpts_shoots'>";
		foreach ($taxonomies as $seasons_and_events){
			if ( $seasons_and_events->parent == 0 ){
				echo "<li class='season'>";
				echo esc_attr($seasons_and_events->name);
				$children = get_term_children($seasons_and_events->term_id , 'wpts_shoots');
				echo "<ul>";
				if (! empty($children)) {
					foreach ($children as $event){
						$anevent = get_term($event, 'wpts_shoots');
						echo "<li>";
						echo "<input type='radio' name='shoot' ";
						if (isset($shoot) && $shoot == $anevent->term_id)
							echo 'checked="checked"';
						echo " value=".esc_attr($anevent->term_id).">".esc_attr($anevent->name);
						echo "</li>";
					}
				}
				echo "<li>";
				echo "</li></ul>";
				echo '</li>';
			}
		}
		echo "</ul>";

	}

	function wpts_process_score($result){
	$score = 0;
	$shoot_result = '';
	for($a = 0; $a <= 99; $a++){
			if ( isset( $result{$a} ) ){
				$score++;
				$shoot_result .= '1';
			}
			else {
				$shoot_result .= '0';
				if ( ! isset( $first_miss) )
					$first_miss = ($a + 1);
			}
		}
	$data['score'] = $score;
	$data['result'] = $shoot_result;
	if (isset($first_miss) )
		$data['first_miss'] = $first_miss;
	else
		$data['first_miss'] = 'false';
	return $data;
	}

	function wpts_record_shoot_form_process($shooter, $shoot, $result, $update = false){
	$score = wpts_process_score($result);
	$blurb = 'words';
    $data = array('post_status' => 'draft', 'post_type' => 'wpts_shoot', 'post_author' => $shooter,
          'ping_status' => get_option('default_ping_status'), 'post_parent' => 0,
          'menu_order' => 0, 'to_ping' =>  false, 'pinged' => '', 'post_password' => '',
          'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0,
		  'post_title' => $score['score'], 'post_name' => $score['result'], 'post_content' => $blurb,
		  'post_category' => $shoot
		  );

	if (! $update) {
		$shoot_id = wp_insert_post($data);
	} else {
		$data['ID'] = $update;
		$shoot_id  = wp_update_post($data);
	}
	if ($shoot_id == 0){
		$error[0] = false;
		$error[1] = 'Insert Data FAIL!';

		return $error;
		break;
	}

	add_post_meta( $shoot_id, 'first_miss', $score['first_miss'] );


	$data[0] = 'shoot added';
	$shoot = (int) $shoot;
	$data[] = wp_set_object_terms($shoot_id, $shoot, 'wpts_shoots');
	return $data;


	}

	function wpts_record_shoot_form($shooter =0, $shoot= '0', $result= '1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111', $add_or_edit = 'add', $individual_shoot_id = false ){
		echo "<h2>the form for adding the results of a shoot</h2>";
		$defaults = array(
           'show_option_all' => '', 'show_option_none' => '',
           'orderby' => 'display_name', 'order' => 'ASC',
           'include' => '', 'exclude' => '', 'multi' => 0,
           'show' => 'display_name', 'echo' => 1,
           'selected' => $shooter, 'name' => 'user', 'class' => ''
		);

		echo "<form action='edit.php?page=wpts_record_shoot' method='post'  >Select Shooter:";

		wp_nonce_field( 'wpts_record_shoot', '_wpts_noonce');
		wp_dropdown_users($defaults);
		wpts_shoot_select_lists($shoot);


		echo "<table id='wpts_score_input'>";

		wpts_score_input($result);
		echo "</table>";
		if ($individual_shoot_id)
			echo "<input type='hidden' name='individual_shoot_id' value='$individual_shoot_id'>";
		echo "<input type='submit' name='action' value='$add_or_edit Shoot'>
		</form>";

	}

	function wpts_edit_shoot(){

		$nonce= wp_create_nonce('wpts_edit_shoot');

		switch (is_request('action') ) {
			case 'cat_select':
				$shootdata = wpts_get_shoot_data( is_request('shoot') );
				echo "<h2>Click on the shoot from ".$shootdata[0]['shoot_name']." that you would like to edit</h2>";
				foreach ($shootdata as $shoot){
					wpts_edit_shoot_link($shoot['id'], $shoot['shooter_name'], $shoot['score'], $shoot['shoot_id'], $nonce);
					//echo $shoot['shooter_name'].' - '.$shoot['score'].'<br />';
					echo "<br />";
				}
				break;
			case 'edit_shoot':
				echo "<h2>Click on the score you would like to edit</h2>";
				$shootdata = wpts_get_shoot_data(is_request('shootid'), is_request('individualshootid') );
				foreach ($shootdata as $shoot) {
					wpts_record_shoot_form($shoot['shooter_id'], $shoot['shoot_id'], $shoot['result'], 'Edit', $shoot['id'] );
					echo "<br />";
				}
				break;
			default:
				echo "<h2>Choose a shoot to edit </h2>";
				echo "<form method='post'>";
				wpts_shoot_select_lists();
				echo "<input type='hidden' name='action' value='cat_select' />
				<input class='choosesubmit' type='submit' name='submit' value='Choose Event' /> </form>";
		}
	}

	function wpts_edit_shoot_link($id, $name, $score, $shootid, $nonce){
	echo "<a href='edit.php?page=wpts_edit_shoot&action=edit_shoot&shootid=$shootid&individualshootid=$id&_wpnonce=$nonce'>$name - $score</a>";
}

	function wpts_edit_season_link($id, $name, $nonce){
	echo "<a href='edit.php?page=wpts_configure_shooting_event&action=edit_season&seasonid=$id&_wpnonce=$nonce'>$name</a>";

}

	function wpts_edit_shoot_info_link($id, $name, $nonce){
	echo "<a href='edit.php?page=wpts_configure_shooting_event&action=edit_event&eventid=$id&_wpnonce=$nonce'>$name</a>";
}

	function wpts_new_shoot_info_link($parentid, $nonce){
	echo "<a href='edit.php?page=wpts_configure_shooting_event&action=new_event&parentid=$parentid&_wpnonce=$nonce'>Add New Event</a>";
}

	function wpts_season_event_form($is_season = true , $parent_id = 0, $current_id  = false ){
		if ($is_season){
			$season_or_event = 'season';
			if ($current_id){
				$event = get_term($current_id, 'wpts_shoots');
				$name = "value='".$event->name ."'";
				$current = 'do_edit_';
				$id = "<input type='hidden' name='currentID' value='".$event->term_id."'";
			} else {
				$name = 'value=""';
				$current = 'add_new_';
				$id ="";
				$new_season_id = $parent_id;
			}
		} elseif ($current_id){
			$event = get_term($current_id, 'wpts_shoots');
			$eventname = esc_attr($event->name);
			$name = "value='$eventname'";
			$current = 'do_edit_';
			$id = "<input type='hidden' name='currentID' value='".$event->term_id."'";
			$season_or_event = 'event';
			$new_season_id = $current_id;
			$shootinfo = unserialize($event->description);
		} else {
			$name = 'value=""';
			$current = 'add_new_';
			$id ="";
			$new_season_id = $parent_id;
			$season_or_event = 'event';
			$shootinfo['date'] = '';
		}

		echo "<form>";
		echo "Name of event: <input name='".$season_or_event."name' $name>";
		echo "<input type='hidden' name='action' value='".$current.$season_or_event."'>";
		echo "<input type='hidden' name='page' value='wpts_configure_shooting_event'>";
		wp_nonce_field('wpts_configure_shooting_event');
		if ($season_or_event == 'event')
			echo "<input type='hidden' name='parent' value='$new_season_id'>";
		echo $id;
		echo "<br />";
		if ( $season_or_event == 'event' ){
			echo "Date of shoot(yyyy/mm/dd): <input name='date' value='".$shootinfo['date']."'><br />";
		} else {
			//$vara = wpts_wwtsl_shoots_for_classes($event->term_id);
			//var_dump($vara);
		}
		echo "<input type='submit' name='submit' value='".str_replace('_',' ' , $current).$season_or_event."'>";
		echo "</form>";

	}

	function wpts_configure_shooting_event(){

		echo '<h2>This screen allows you to edit and add new Seasons and events </h2>';
		echo '<div id="wpts_shoot">';

$action = is_get('action');
if (strlen($action) != 0 ){
		$nonce= is_request('_wpnonce');
		if (strlen($nonce) != 0 ) {
			if (! wp_verify_nonce($nonce, 'wpts_configure_shooting_event') ) die('Security check');
		} else {
			check_admin_referer( 'wpts_configure_shooting_event');
		}
}
$nonce= wp_create_nonce('wpts_configure_shooting_event');

switch ($action) {
	case 'new_season':
		echo "<p>Please fill out all data and hit submit to add a new season.  In the next step you'll have the opportunity to start adding events to this season.</p>";
		wpts_season_event_form();
		break;

	case 'add_new_season':
		$name = is_request('seasonname');
		$args = array();
		$new_season = wp_insert_term( addslashes_gpc($name), 'wpts_shoots', $args  );
		$new_season_id = $new_season['term_id'];
		echo "<p>$name has been added as a new season.  Please add your first event below as a child to $new_season_id</p>";
	wpts_season_event_form(false , $new_season_id);
		break;

	case 'add_new_event':
		$name = is_request('eventname');
		$data['date'] = is_request('date');
		$description = serialize($data);
		$args = array( 'parent' => is_request('parent'), 'description' => $description );
		$new_season_id = wp_insert_term( addslashes_gpc($name), 'wpts_shoots', $args  );
		echo "<p>$name has been added as a new event.  You can use the form below to add another event</p>";
		wpts_season_event_form(false , is_request('parent'));

		break;
	case 'new_event':
		echo "<p>Use the form below to add an Event</p>";
		wpts_season_event_form(false , is_request('parentid'));
		break;
	case 'add_event':
		echo "<p>Use the form below to add an Event</p>";
		wpts_season_event_form(false , is_request('parentid'));
		break;
	case 'do_edit_season':
		$term_id = (int) is_request('currentID');
		$args = array('name' => addslashes_gpc( is_request('seasonname') ), 'term_id' => $term_id );
		wpts_update_term($args);
		wpts_empty_table_cache(is_request('currentID'));
		break;

	case 'do_edit_event':
		$data['date'] = is_request('date');
		$description = serialize($data);
		$term_id = (int) is_request('currentID');
		$args = array('name' => addslashes_gpc( is_request('eventname') ), 'description' => "$description", 'term_id' => $term_id );
		$update =  wpts_update_term($args);
		echo "You have successfully updated ".is_request('eventname') ;
		$parent_id = get_term_by('id', $term_id, 'wpts_shoots', $output = ARRAY_A);
		wpts_empty_table_cache($parent_id['parent']);

		break;
	case 'edit_season':
		wpts_season_event_form(true , $parent_id = 0, is_request('seasonid') );
		break;

	case 'edit_event':
		wpts_season_event_form(false, 0, is_request('eventid') );
		break;

	default:


$newseason = "<a href='edit.php?page=wpts_configure_shooting_event&action=new_season&_wpnonce=$nonce'>New Season</a>";


		echo '<p>Please click on season or event to edit it or click the appropriate add button</p><ul>
	';
$args= array('orderby' => 'name', 'order' => 'ASC',
        'hide_empty' => false, 'exclude' => '', 'exclude_tree' => '', 'include' => '',
        'number' => '', 'fields' => 'all', 'slug' => '', 'parent' => '',
        'hierarchical' => true, 'child_of' => 0, 'get' => '', 'name__like' => '',
        'pad_counts' => false, 'offset' => '', 'search' => '');

	$taxonomies = get_terms('wpts_shoots', $args);
	foreach ($taxonomies as $seasons_and_events){
		if ( $seasons_and_events->parent == 0 ){
			echo "<li>";
			wpts_edit_season_link($seasons_and_events->term_id, $seasons_and_events->name,  $nonce);
			$children = get_term_children($seasons_and_events->term_id , 'wpts_shoots');
			echo "<ul>";
			if (! empty($children)) {
				foreach ($children as $event){
					$anevent = get_term($event, 'wpts_shoots');
					echo "<li>";
					wpts_edit_shoot_info_link($anevent->term_id, $anevent->name, $nonce);
					echo "&nbsp;&nbsp;[target_shoot shoot_id='".$anevent->term_id."']";
					echo "</li>";
				}
			}
			echo "<li>";
			wpts_new_shoot_info_link($seasons_and_events->term_id, $nonce);
			echo "</li></ul>";
			echo '</li>';
		}
	}
echo '	<li>'.$newseason.'</li></ul></div>
';
	}
}

	function wpts_update_term($args, $taxonomy = 'wpts_shoots' ){

wp_update_term($args['term_id'], $taxonomy, $args);

}

	function wpts_score_input($current = '1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111'){
$count = 0;
echo '<thead><tr><th colspan="25">Boxes marked with checks are hit targets</th></tr></thead>';
for ($round = 1; $round <= 4; $round++){
	echo "<thead><tr><th colspan='25'>Round $round</th></tr></thead>
			  <tr>
				  <td colspan='2' >1 </td>
				  <td colspan='2' >DBLS</td>
				  <td colspan='2' >2 </td>
				  <td colspan='2' >DBLS</td>
				  <td colspan='2' >3</td>
				  <td colspan='2' >4</td>
				  <td colspan='2' >5</td>
				  <td colspan='2' >6</td>
				  <td colspan='2' >DBLS</td>
				  <td colspan='2' >7</td>
				  <td colspan='2' >DBLS</td>
				  <td colspan='2' >8</td>
			  </tr>
			  <tr>
				<td>H</td>
				<td>L</td>
				<td>H</td>
				<td>L</td>
				<td>H</td>
				<td>L</td>
				<td>H</td>
				<td>L</td>
				<td>H</td>
				<td>L</td>
				<td>H</td>
				<td>L</td>
				<td>H</td>
				<td>L</td>
				<td>H</td>
				<td>L</td>
				<td>L</td>
				<td>H</td>
				<td>H</td>
				<td>L</td>
				<td>L</td>
				<td>H</td>
				<td>H</td>
				<td>L</td>
				<td>opt</td>
			  </tr>
			  <tr>
			  ";
			for ($a = 0; $a <= 24; $a++){
				if ($current{$count} == 1)
					$checked = 'checked="checked"';
				else
					$checked = '';
				echo "<td><input type='checkbox' name='wpts_score[$count]' $checked> </td>";
				$count++;
			}
			echo "</tr>";

	}
}

function wpts_empty_table_cache($season_id){
// when done, it should remove all of the cached result tables from the database for that season
	$shoots = wpts_get_season_shoots($season_id);
	foreach ($shoots as $shoot){
		$option_name = "wpts_shoot_table_".$shoot['term_id'];
		if ( get_option($option_name) ){
			delete_option($option_name);

		}
	}

}

}
?>